﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace AnycleLiu.Common.Utils
{
    /// <summary>
    /// 对象映射工具类
    /// </summary>
    public static class ObjectMappingUtil
    {
        /// <summary>
        /// 将t1对象的公共属性值复制到t2对象（只复制相同名字的属性）
        /// </summary>
        /// <typeparam name="T1">源类型</typeparam>
        /// <typeparam name="T2">目标类型</typeparam>
        /// <param name="t1">源对象</param>
        /// <returns>目标对象</returns>
        public static T2 Mapping<T1, T2>(T1 t1)
            where T1 : new()
            where T2 : new()
        {
            var t2 = new T2();
            var type2 = t2.GetType();
            var properties = t1.GetType().GetProperties();
            foreach (var property in properties)
            {
                type2.GetProperty(property.Name).SetValue(t2, property.GetValue(t1, null), null);
            }
            return t2;
        }
        public static void PrintObject<T>(T t)
        {
            var properties = t.GetType().GetProperties();
            Console.WriteLine(string.Format("-----{0}", t.GetType().Name));

            foreach (var property in properties)
            {
                Console.WriteLine(string.Format("{0}:{1}", property.Name, property.GetValue(t, null)));
            }
        }
    }
}
